#include "tcp.h"

typedef struct
{
	int type;
	int opt;
}MSG;

int Manual_led(int sockfd,MSG *msg)
{
	while(1)
	{
		msg->type='M';
		printf("----Manual operation-----\n");
		printf("---0.OFF  1.ON  2.exit---\n");
		printf(">>>>please choose:");
		scanf("%d",&msg->opt);
		getchar();
		if(msg->opt==2)
			break;
		switch(msg->opt)
		{
		case 0:
			if(send(sockfd,msg,sizeof(MSG),0)<0)
			{
				perror("send");
				return -1;
			}
			break;
		case 1:
			if(send(sockfd,msg,sizeof(MSG),0)<0)
			{
				perror("send");
				return -1;
			}
			break;
		default:
			printf("Invalid num!\n");
		}
	}
	return 0;
}

int Auto_led(int sockfd,MSG *msg)
{
	msg->type='A';
	printf("----Auto operation---\n");
	if(send(sockfd,msg,sizeof(MSG),0)<0)
	{
		perror("send");
		exit(-1);
	}
	return 0;

}

int main(int argc, const char *argv[])
{
	int n;
	int sockfd;
	MSG msg;
	struct sockaddr_in serveraddr;
	if(argc<3)
	{
		printf("Usage : %s <IP> <port>\n",argv[0]);
		return -1;
	}
	if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
	{
		perror("socket");
		exit(-1);
	}
	bzero(&serveraddr,sizeof(serveraddr));
	serveraddr.sin_family=AF_INET;
	serveraddr.sin_port=htons(atoi(argv[2]));
	serveraddr.sin_addr.s_addr=inet_addr(argv[1]);
	if(connect(sockfd,(struct sockaddr *)&serveraddr,sizeof(serveraddr))<0)
	{
		perror("connect");
		exit(-1);
	}

	while(1)
	{
		printf("********************************\n");
		printf("***This is a led system ********\n");
		printf("***1 Manual  2 Auto  3 exit*****\n");
		printf("********************************\n");
		printf("please choose:");
		scanf("%d",&n);
		getchar();
		if(n==3)
		{
			close(sockfd);
			exit(0);
		}
		switch(n)
		{
			case 1:
				Manual_led(sockfd,&msg);
				break;
			case 2:
				Auto_led(sockfd,&msg);
				break;
			default:
				printf("Invalid number!\n");
		}
	}
	return 0;
}
